3 * Base code for MediaWiki installer.
5 * DO NOT PATCH THIS FILE IF YOU NEED TO CHANGE INSTALLER BEHAVIOR IN YOUR PACKAGE!
6 * See mw-config/overrides/README for details.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
27 use MediaWiki\Interwiki\NullInterwikiLookup
;
28 use MediaWiki\MediaWikiServices
;
29 use MediaWiki\Shell\Shell
;
32 * This documentation group collects source code files with deployment functionality.
34 * @defgroup Deployment Deployment
38 * Base installer class.
40 * This class provides the base for installation and update functionality
41 * for both MediaWiki core and extensions.
46 abstract class Installer
{
49 * The oldest version of PCRE we can support.
51 * Defining this is necessary because PHP may be linked with a system version
52 * of PCRE, which may be older than that bundled with the minimum PHP version.
54 const MINIMUM_PCRE_VERSION
= '7.2';
62 * List of detected DBs, access using getCompiledDBs().
66 protected $compiledDBs;
69 * Cached DB installer instances, access using getDBInstaller().
73 protected $dbInstallers = [];
76 * Minimum memory size in MB.
80 protected $minMemorySize = 50;
83 * Cached Title, used by parse().
87 protected $parserTitle;
90 * Cached ParserOptions, used by parse().
94 protected $parserOptions;
97 * Known database types. These correspond to the class names <type>Installer,
98 * and are also MediaWiki database types valid for $wgDBtype.
100 * To add a new type, create a <type>Installer class and a Database<type>
101 * class, and add a config-type-<type> message to MessagesEn.php.
105 protected static $dbTypes = [
114 * A list of environment check methods called by doEnvironmentChecks().
115 * These may output warnings using showMessage(), and/or abort the
116 * installation process by returning false.
118 * For the WebInstaller these are only called on the Welcome page,
119 * if these methods have side-effects that should affect later page loads
120 * (as well as the generated stylesheet), use envPreps instead.
124 protected $envChecks = [
130 'envCheckModSecurity',
136 'envCheckShellLocale',
137 'envCheckUploadsDirectory',
139 'envCheckSuhosinMaxValueLength',
144 * A list of environment preparation methods called by doEnvironmentPreps().
148 protected $envPreps = [
154 * MediaWiki configuration globals that will eventually be passed through
155 * to LocalSettings.php. The names only are given here, the defaults
156 * typically come from DefaultSettings.php.
160 protected $defaultVarNames = [
171 'wgEmailAuthentication',
175 'wgImageMagickConvertCommand',
180 'wgDeletedDirectory',
184 'wgUseInstantCommons',
191 * Variables that are stored alongside globals, and are used for any
192 * configuration of the installation process aside from the MediaWiki
193 * configuration. Map of names to defaults.
197 protected $internalDefaults = [
199 '_Environment' => false,
200 '_RaiseMemory' => false,
201 '_UpgradeDone' => false,
202 '_InstallDone' => false,
204 '_InstallPassword' => '',
205 '_SameAccount' => true,
206 '_CreateDBAccount' => false,
207 '_NamespaceType' => 'site-name',
208 '_AdminName' => '', // will be set later, when the user selects language
209 '_AdminPassword' => '',
210 '_AdminPasswordConfirm' => '',
212 '_Subscribe' => false,
213 '_SkipOptional' => 'continue',
214 '_RightsProfile' => 'wiki',
215 '_LicenseCode' => 'none',
219 '_MemCachedServers' => '',
220 '_UpgradeKeySupplied' => false,
221 '_ExistingDBSettings' => false,
223 // $wgLogo is probably wrong (T50084); set something that will work.
224 // Single quotes work fine here, as LocalSettingsGenerator outputs this unescaped.
225 'wgLogo' => '$wgResourceBasePath/resources/assets/wiki.png',
226 'wgAuthenticationTokenVersion' => 1,
230 * The actual list of installation steps. This will be initialized by getInstallSteps()
234 private $installSteps = [];
237 * Extra steps for installation, for things like DatabaseInstallers to modify
241 protected $extraInstallSteps = [];
244 * Known object cache types and the functions used to test for their existence.
248 protected $objectCaches = [
249 'apc' => 'apc_fetch',
250 'apcu' => 'apcu_fetch',
251 'wincache' => 'wincache_ucache_get'
255 * User rights profiles.
259 public $rightsProfiles = [
262 '*' => [ 'edit' => false ]
266 'createaccount' => false,
272 'createaccount' => false,
286 'url' => 'https://creativecommons.org/licenses/by/4.0/',
287 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by.png',
290 'url' => 'https://creativecommons.org/licenses/by-sa/4.0/',
291 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-sa.png',
294 'url' => 'https://creativecommons.org/licenses/by-nc-sa/4.0/',
295 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-by-nc-sa.png',
298 'url' => 'https://creativecommons.org/publicdomain/zero/1.0/',
299 'icon' => '$wgResourceBasePath/resources/assets/licenses/cc-0.png',
302 'url' => 'https://www.gnu.org/copyleft/fdl.html',
303 'icon' => '$wgResourceBasePath/resources/assets/licenses/gnu-fdl.png',
311 // Details will be filled in by the selector.
319 * URL to mediawiki-announce subscription
321 protected $mediaWikiAnnounceUrl =
322 'https://lists.wikimedia.org/mailman/subscribe/mediawiki-announce';
325 * Supported language codes for Mailman
327 protected $mediaWikiAnnounceLanguages = [
328 'ca', 'cs', 'da', 'de', 'en', 'es', 'et', 'eu', 'fi', 'fr', 'hr', 'hu',
329 'it', 'ja', 'ko', 'lt', 'nl', 'no', 'pl', 'pt', 'pt-br', 'ro', 'ru',
330 'sl', 'sr', 'sv', 'tr', 'uk'
334 * UI interface for displaying a short message
335 * The parameters are like parameters to wfMessage().
336 * The messages will be in wikitext format, which will be converted to an
337 * output format such as HTML or text before being sent to the user.
340 abstract public function showMessage( $msg /*, ... */ );
343 * Same as showMessage(), but for displaying errors
346 abstract public function showError( $msg /*, ... */ );
349 * Show a message to the installing user by using a Status object
350 * @param Status $status
352 abstract public function showStatusMessage( Status
$status );
355 * Constructs a Config object that contains configuration settings that should be
356 * overwritten for the installation process.
360 * @param Config $baseConfig
362 * @return Config The config to use during installation.
364 public static function getInstallerConfig( Config
$baseConfig ) {
365 $configOverrides = new HashConfig();
367 // disable (problematic) object cache types explicitly, preserving all other (working) ones
369 $emptyCache = [ 'class' => EmptyBagOStuff
::class ];
372 CACHE_NONE
=> $emptyCache,
373 CACHE_DB
=> $emptyCache,
374 CACHE_ANYTHING
=> $emptyCache,
375 CACHE_MEMCACHED
=> $emptyCache,
376 ] +
$baseConfig->get( 'ObjectCaches' );
378 $configOverrides->set( 'ObjectCaches', $objectCaches );
380 // Load the installer's i18n.
381 $messageDirs = $baseConfig->get( 'MessagesDirs' );
382 $messageDirs['MediawikiInstaller'] = __DIR__
. '/i18n';
384 $configOverrides->set( 'MessagesDirs', $messageDirs );
386 $installerConfig = new MultiConfig( [ $configOverrides, $baseConfig ] );
388 // make sure we use the installer config as the main config
389 $configRegistry = $baseConfig->get( 'ConfigRegistry' );
390 $configRegistry['main'] = function () use ( $installerConfig ) {
391 return $installerConfig;
394 $configOverrides->set( 'ConfigRegistry', $configRegistry );
396 return $installerConfig;
400 * Constructor, always call this from child classes.
402 public function __construct() {
403 global $wgMemc, $wgUser, $wgObjectCaches;
405 $defaultConfig = new GlobalVarConfig(); // all the stuff from DefaultSettings.php
406 $installerConfig = self
::getInstallerConfig( $defaultConfig );
408 // Reset all services and inject config overrides
409 MediaWikiServices
::resetGlobalInstance( $installerConfig );
411 // Don't attempt to load user language options (T126177)
412 // This will be overridden in the web installer with the user-specified language
413 RequestContext
::getMain()->setLanguage( 'en' );
415 // Disable the i18n cache
416 // TODO: manage LocalisationCache singleton in MediaWikiServices
417 Language
::getLocalisationCache()->disableBackend();
419 // Disable all global services, since we don't have any configuration yet!
420 MediaWikiServices
::disableStorageBackend();
422 $mwServices = MediaWikiServices
::getInstance();
423 // Disable object cache (otherwise CACHE_ANYTHING will try CACHE_DB and
424 // SqlBagOStuff will then throw since we just disabled wfGetDB)
425 $wgObjectCaches = $mwServices->getMainConfig()->get( 'ObjectCaches' );
426 $wgMemc = ObjectCache
::getInstance( CACHE_NONE
);
428 // Disable interwiki lookup, to avoid database access during parses
429 $mwServices->redefineService( 'InterwikiLookup', function () {
430 return new NullInterwikiLookup();
433 // Having a user with id = 0 safeguards us from DB access via User::loadOptions().
434 $wgUser = User
::newFromId( 0 );
435 RequestContext
::getMain()->setUser( $wgUser );
437 $this->settings
= $this->internalDefaults
;
439 foreach ( $this->defaultVarNames
as $var ) {
440 $this->settings
[$var] = $GLOBALS[$var];
443 $this->doEnvironmentPreps();
445 $this->compiledDBs
= [];
446 foreach ( self
::getDBTypes() as $type ) {
447 $installer = $this->getDBInstaller( $type );
449 if ( !$installer->isCompiled() ) {
452 $this->compiledDBs
[] = $type;
455 $this->parserTitle
= Title
::newFromText( 'Installer' );
456 $this->parserOptions
= new ParserOptions( $wgUser ); // language will be wrong :(
457 $this->parserOptions
->setTidy( true );
458 // Don't try to access DB before user language is initialised
459 $this->setParserLanguage( Language
::factory( 'en' ) );
463 * Get a list of known DB types.
467 public static function getDBTypes() {
468 return self
::$dbTypes;
472 * Do initial checks of the PHP environment. Set variables according to
473 * the observed environment.
475 * It's possible that this may be called under the CLI SAPI, not the SAPI
476 * that the wiki will primarily run under. In that case, the subclass should
477 * initialise variables such as wgScriptPath, before calling this function.
479 * Under the web subclass, it can already be assumed that PHP 5+ is in use
480 * and that sessions are working.
484 public function doEnvironmentChecks() {
485 // Php version has already been checked by entry scripts
486 // Show message here for information purposes
488 $this->showMessage( 'config-env-hhvm', HHVM_VERSION
);
490 $this->showMessage( 'config-env-php', PHP_VERSION
);
494 // Must go here because an old version of PCRE can prevent other checks from completing
495 list( $pcreVersion ) = explode( ' ', PCRE_VERSION
, 2 );
496 if ( version_compare( $pcreVersion, self
::MINIMUM_PCRE_VERSION
, '<' ) ) {
497 $this->showError( 'config-pcre-old', self
::MINIMUM_PCRE_VERSION
, $pcreVersion );
500 foreach ( $this->envChecks
as $check ) {
501 $status = $this->$check();
502 if ( $status === false ) {
508 $this->setVar( '_Environment', $good );
510 return $good ? Status
::newGood() : Status
::newFatal( 'config-env-bad' );
513 public function doEnvironmentPreps() {
514 foreach ( $this->envPreps
as $prep ) {
520 * Set a MW configuration variable, or internal installer configuration variable.
522 * @param string $name
523 * @param mixed $value
525 public function setVar( $name, $value ) {
526 $this->settings
[$name] = $value;
530 * Get an MW configuration variable, or internal installer configuration variable.
531 * The defaults come from $GLOBALS (ultimately DefaultSettings.php).
532 * Installer variables are typically prefixed by an underscore.
534 * @param string $name
535 * @param mixed|null $default
539 public function getVar( $name, $default = null ) {
540 return $this->settings
[$name] ??
$default;
544 * Get a list of DBs supported by current PHP setup
548 public function getCompiledDBs() {
549 return $this->compiledDBs
;
553 * Get the DatabaseInstaller class name for this type
555 * @param string $type database type ($wgDBtype)
556 * @return string Class name
559 public static function getDBInstallerClass( $type ) {
560 return ucfirst( $type ) . 'Installer';
564 * Get an instance of DatabaseInstaller for the specified DB type.
566 * @param mixed $type DB installer for which is needed, false to use default.
568 * @return DatabaseInstaller
570 public function getDBInstaller( $type = false ) {
572 $type = $this->getVar( 'wgDBtype' );
575 $type = strtolower( $type );
577 if ( !isset( $this->dbInstallers
[$type] ) ) {
578 $class = self
::getDBInstallerClass( $type );
579 $this->dbInstallers
[$type] = new $class( $this );
582 return $this->dbInstallers
[$type];
586 * Determine if LocalSettings.php exists. If it does, return its variables.
588 * @return array|false
590 public static function getExistingLocalSettings() {
593 // You might be wondering why this is here. Well if you don't do this
594 // then some poorly-formed extensions try to call their own classes
595 // after immediately registering them. We really need to get extension
596 // registration out of the global scope and into a real format.
597 // @see https://phabricator.wikimedia.org/T69440
598 global $wgAutoloadClasses;
599 $wgAutoloadClasses = [];
601 // LocalSettings.php should not call functions, except wfLoadSkin/wfLoadExtensions
602 // Define the required globals here, to ensure, the functions can do it work correctly.
603 // phpcs:ignore MediaWiki.VariableAnalysis.UnusedGlobalVariables
604 global $wgExtensionDirectory, $wgStyleDirectory;
606 Wikimedia\
suppressWarnings();
607 $_lsExists = file_exists( "$IP/LocalSettings.php" );
608 Wikimedia\restoreWarnings
();
615 require "$IP/includes/DefaultSettings.php";
616 require "$IP/LocalSettings.php";
618 return get_defined_vars();
622 * Get a fake password for sending back to the user in HTML.
623 * This is a security mechanism to avoid compromise of the password in the
624 * event of session ID compromise.
626 * @param string $realPassword
630 public function getFakePassword( $realPassword ) {
631 return str_repeat( '*', strlen( $realPassword ) );
635 * Set a variable which stores a password, except if the new value is a
636 * fake password in which case leave it as it is.
638 * @param string $name
639 * @param mixed $value
641 public function setPassword( $name, $value ) {
642 if ( !preg_match( '/^\*+$/', $value ) ) {
643 $this->setVar( $name, $value );
648 * On POSIX systems return the primary group of the webserver we're running under.
649 * On other systems just returns null.
651 * This is used to advice the user that he should chgrp his mw-config/data/images directory as the
652 * webserver user before he can install.
654 * Public because SqliteInstaller needs it, and doesn't subclass Installer.
658 public static function maybeGetWebserverPrimaryGroup() {
659 if ( !function_exists( 'posix_getegid' ) ||
!function_exists( 'posix_getpwuid' ) ) {
660 # I don't know this, this isn't UNIX.
664 # posix_getegid() *not* getmygid() because we want the group of the webserver,
665 # not whoever owns the current script.
666 $gid = posix_getegid();
667 $group = posix_getpwuid( $gid )['name'];
673 * Convert wikitext $text to HTML.
675 * This is potentially error prone since many parser features require a complete
676 * installed MW database. The solution is to just not use those features when you
677 * write your messages. This appears to work well enough. Basic formatting and
678 * external links work just fine.
680 * But in case a translator decides to throw in a "#ifexist" or internal link or
681 * whatever, this function is guarded to catch the attempted DB access and to present
682 * some fallback text.
684 * @param string $text
685 * @param bool $lineStart
688 public function parse( $text, $lineStart = false ) {
689 $parser = MediaWikiServices
::getInstance()->getParser();
692 $out = $parser->parse( $text, $this->parserTitle
, $this->parserOptions
, $lineStart );
693 $html = $out->getText( [
694 'enableSectionEditLinks' => false,
697 } catch ( Wikimedia\Services\ServiceDisabledException
$e ) {
698 $html = '<!--DB access attempted during parse--> ' . htmlspecialchars( $text );
705 * @return ParserOptions
707 public function getParserOptions() {
708 return $this->parserOptions
;
711 public function disableLinkPopups() {
712 $this->parserOptions
->setExternalLinkTarget( false );
715 public function restoreLinkPopups() {
716 global $wgExternalLinkTarget;
717 $this->parserOptions
->setExternalLinkTarget( $wgExternalLinkTarget );
721 * Install step which adds a row to the site_stats table with appropriate
724 * @param DatabaseInstaller $installer
728 public function populateSiteStats( DatabaseInstaller
$installer ) {
729 $status = $installer->getConnection();
730 if ( !$status->isOK() ) {
733 $status->value
->insert(
737 'ss_total_edits' => 0,
738 'ss_good_articles' => 0,
739 'ss_total_pages' => 0,
741 'ss_active_users' => 0,
747 return Status
::newGood();
751 * Environment check for DB types.
754 protected function envCheckDB() {
759 // Messages: config-type-mysql, config-type-postgres, config-type-oracle,
760 // config-type-sqlite
761 foreach ( self
::getDBTypes() as $name ) {
762 $allNames[] = wfMessage( "config-type-$name" )->text();
765 $databases = $this->getCompiledDBs();
767 $databases = array_flip( $databases );
768 foreach ( array_keys( $databases ) as $db ) {
769 $installer = $this->getDBInstaller( $db );
770 $status = $installer->checkPrerequisites();
771 if ( !$status->isGood() ) {
772 $this->showStatusMessage( $status );
774 if ( !$status->isOK() ) {
775 unset( $databases[$db] );
778 $databases = array_flip( $databases );
780 $this->showError( 'config-no-db', $wgLang->commaList( $allNames ), count( $allNames ) );
782 // @todo FIXME: This only works for the web installer!
790 * Some versions of libxml+PHP break < and > encoding horribly
793 protected function envCheckBrokenXML() {
794 $test = new PhpXmlBugTester();
796 $this->showError( 'config-brokenlibxml' );
805 * Environment check for the PCRE module.
807 * @note If this check were to fail, the parser would
808 * probably throw an exception before the result
809 * of this check is shown to the user.
812 protected function envCheckPCRE() {
813 Wikimedia\
suppressWarnings();
814 $regexd = preg_replace( '/[\x{0430}-\x{04FF}]/iu', '', '-АБВГД-' );
815 // Need to check for \p support too, as PCRE can be compiled
816 // with utf8 support, but not unicode property support.
817 // check that \p{Zs} (space separators) matches
818 // U+3000 (Ideographic space)
819 $regexprop = preg_replace( '/\p{Zs}/u', '', "-\u{3000}-" );
820 Wikimedia\restoreWarnings
();
821 if ( $regexd != '--' ||
$regexprop != '--' ) {
822 $this->showError( 'config-pcre-no-utf8' );
831 * Environment check for available memory.
834 protected function envCheckMemory() {
835 $limit = ini_get( 'memory_limit' );
837 if ( !$limit ||
$limit == -1 ) {
841 $n = wfShorthandToInteger( $limit );
843 if ( $n < $this->minMemorySize
* 1024 * 1024 ) {
844 $newLimit = "{$this->minMemorySize}M";
846 if ( ini_set( "memory_limit", $newLimit ) === false ) {
847 $this->showMessage( 'config-memory-bad', $limit );
849 $this->showMessage( 'config-memory-raised', $limit, $newLimit );
850 $this->setVar( '_RaiseMemory', true );
858 * Environment check for compiled object cache types.
860 protected function envCheckCache() {
862 foreach ( $this->objectCaches
as $name => $function ) {
863 if ( function_exists( $function ) ) {
864 $caches[$name] = true;
869 $this->showMessage( 'config-no-cache-apcu' );
872 $this->setVar( '_Caches', $caches );
876 * Scare user to death if they have mod_security or mod_security2
879 protected function envCheckModSecurity() {
880 if ( self
::apacheModulePresent( 'mod_security' )
881 || self
::apacheModulePresent( 'mod_security2' ) ) {
882 $this->showMessage( 'config-mod-security' );
889 * Search for GNU diff3.
892 protected function envCheckDiff3() {
893 $names = [ "gdiff3", "diff3" ];
894 if ( wfIsWindows() ) {
895 $names[] = 'diff3.exe';
897 $versionInfo = [ '--version', 'GNU diffutils' ];
899 $diff3 = ExecutableFinder
::findInDefaultPaths( $names, $versionInfo );
902 $this->setVar( 'wgDiff3', $diff3 );
904 $this->setVar( 'wgDiff3', false );
905 $this->showMessage( 'config-diff3-bad' );
912 * Environment check for ImageMagick and GD.
915 protected function envCheckGraphics() {
916 $names = wfIsWindows() ?
'convert.exe' : 'convert';
917 $versionInfo = [ '-version', 'ImageMagick' ];
918 $convert = ExecutableFinder
::findInDefaultPaths( $names, $versionInfo );
920 $this->setVar( 'wgImageMagickConvertCommand', '' );
922 $this->setVar( 'wgImageMagickConvertCommand', $convert );
923 $this->showMessage( 'config-imagemagick', $convert );
926 } elseif ( function_exists( 'imagejpeg' ) ) {
927 $this->showMessage( 'config-gd' );
929 $this->showMessage( 'config-no-scaling' );
941 protected function envCheckGit() {
942 $names = wfIsWindows() ?
'git.exe' : 'git';
943 $versionInfo = [ '--version', 'git version' ];
945 $git = ExecutableFinder
::findInDefaultPaths( $names, $versionInfo );
948 $this->setVar( 'wgGitBin', $git );
949 $this->showMessage( 'config-git', $git );
951 $this->setVar( 'wgGitBin', false );
952 $this->showMessage( 'config-git-bad' );
959 * Environment check to inform user which server we've assumed.
963 protected function envCheckServer() {
964 $server = $this->envGetDefaultServer();
965 if ( $server !== null ) {
966 $this->showMessage( 'config-using-server', $server );
972 * Environment check to inform user which paths we've assumed.
976 protected function envCheckPath() {
979 $this->getVar( 'wgServer' ),
980 $this->getVar( 'wgScriptPath' )
986 * Environment check for preferred locale in shell
989 protected function envCheckShellLocale() {
990 $os = php_uname( 's' );
991 $supported = [ 'Linux', 'SunOS', 'HP-UX', 'Darwin' ]; # Tested these
993 if ( !in_array( $os, $supported ) ) {
997 if ( Shell
::isDisabled() ) {
1001 # Get a list of available locales.
1002 $result = Shell
::command( '/usr/bin/locale', '-a' )
1005 if ( $result->getExitCode() != 0 ) {
1009 $lines = $result->getStdout();
1010 $lines = array_map( 'trim', explode( "\n", $lines ) );
1011 $candidatesByLocale = [];
1012 $candidatesByLang = [];
1013 foreach ( $lines as $line ) {
1014 if ( $line === '' ) {
1018 if ( !preg_match( '/^([a-zA-Z]+)(_[a-zA-Z]+|)\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m ) ) {
1022 list( , $lang, , , ) = $m;
1024 $candidatesByLocale[$m[0]] = $m;
1025 $candidatesByLang[$lang][] = $m;
1028 # Try the current value of LANG.
1029 if ( isset( $candidatesByLocale[getenv( 'LANG' )] ) ) {
1030 $this->setVar( 'wgShellLocale', getenv( 'LANG' ) );
1035 # Try the most common ones.
1036 $commonLocales = [ 'C.UTF-8', 'en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8' ];
1037 foreach ( $commonLocales as $commonLocale ) {
1038 if ( isset( $candidatesByLocale[$commonLocale] ) ) {
1039 $this->setVar( 'wgShellLocale', $commonLocale );
1045 # Is there an available locale in the Wiki's language?
1046 $wikiLang = $this->getVar( 'wgLanguageCode' );
1048 if ( isset( $candidatesByLang[$wikiLang] ) ) {
1049 $m = reset( $candidatesByLang[$wikiLang] );
1050 $this->setVar( 'wgShellLocale', $m[0] );
1055 # Are there any at all?
1056 if ( count( $candidatesByLocale ) ) {
1057 $m = reset( $candidatesByLocale );
1058 $this->setVar( 'wgShellLocale', $m[0] );
1068 * Environment check for the permissions of the uploads directory
1071 protected function envCheckUploadsDirectory() {
1074 $dir = $IP . '/images/';
1075 $url = $this->getVar( 'wgServer' ) . $this->getVar( 'wgScriptPath' ) . '/images/';
1076 $safe = !$this->dirIsExecutable( $dir, $url );
1079 $this->showMessage( 'config-uploads-not-safe', $dir );
1086 * Checks if suhosin.get.max_value_length is set, and if so generate
1087 * a warning because it decreases ResourceLoader performance.
1090 protected function envCheckSuhosinMaxValueLength() {
1091 $maxValueLength = ini_get( 'suhosin.get.max_value_length' );
1092 if ( $maxValueLength > 0 && $maxValueLength < 1024 ) {
1093 // Only warn if the value is below the sane 1024
1094 $this->showMessage( 'config-suhosin-max-value-length', $maxValueLength );
1101 * Checks if we're running on 64 bit or not. 32 bit is becoming increasingly
1102 * hard to support, so let's at least warn people.
1106 protected function envCheck64Bit() {
1107 if ( PHP_INT_SIZE
== 4 ) {
1108 $this->showMessage( 'config-using-32bit' );
1115 * Check the libicu version
1117 protected function envCheckLibicu() {
1119 * This needs to be updated something that the latest libicu
1120 * will properly normalize. This normalization was found at
1121 * https://www.unicode.org/versions/Unicode5.2.0/#Character_Additions
1122 * Note that we use the hex representation to create the code
1123 * points in order to avoid any Unicode-destroying during transit.
1125 $not_normal_c = "\u{FA6C}";
1126 $normal_c = "\u{242EE}";
1128 $useNormalizer = 'php';
1129 $needsUpdate = false;
1131 if ( function_exists( 'normalizer_normalize' ) ) {
1132 $useNormalizer = 'intl';
1133 $intl = normalizer_normalize( $not_normal_c, Normalizer
::FORM_C
);
1134 if ( $intl !== $normal_c ) {
1135 $needsUpdate = true;
1139 // Uses messages 'config-unicode-using-php' and 'config-unicode-using-intl'
1140 if ( $useNormalizer === 'php' ) {
1141 $this->showMessage( 'config-unicode-pure-php-warning' );
1143 $this->showMessage( 'config-unicode-using-' . $useNormalizer );
1144 if ( $needsUpdate ) {
1145 $this->showMessage( 'config-unicode-update-warning' );
1151 * Environment prep for the server hostname.
1153 protected function envPrepServer() {
1154 $server = $this->envGetDefaultServer();
1155 if ( $server !== null ) {
1156 $this->setVar( 'wgServer', $server );
1161 * Helper function to be called from envPrepServer()
1164 abstract protected function envGetDefaultServer();
1167 * Environment prep for setting $IP and $wgScriptPath.
1169 protected function envPrepPath() {
1171 $IP = dirname( dirname( __DIR__
) );
1172 $this->setVar( 'IP', $IP );
1176 * Checks if scripts located in the given directory can be executed via the given URL.
1178 * Used only by environment checks.
1179 * @param string $dir
1180 * @param string $url
1181 * @return bool|int|string
1183 public function dirIsExecutable( $dir, $url ) {
1186 "<?php echo 'exec';",
1187 "#!/var/env php\n<?php echo 'exec';",
1191 // it would be good to check other popular languages here, but it'll be slow.
1193 Wikimedia\
suppressWarnings();
1195 foreach ( $scriptTypes as $ext => $contents ) {
1196 foreach ( $contents as $source ) {
1197 $file = 'exectest.' . $ext;
1199 if ( !file_put_contents( $dir . $file, $source ) ) {
1204 $text = Http
::get( $url . $file, [ 'timeout' => 3 ], __METHOD__
);
1205 } catch ( Exception
$e ) {
1206 // Http::get throws with allow_url_fopen = false and no curl extension.
1209 unlink( $dir . $file );
1211 if ( $text == 'exec' ) {
1212 Wikimedia\restoreWarnings
();
1219 Wikimedia\restoreWarnings
();
1225 * Checks for presence of an Apache module. Works only if PHP is running as an Apache module, too.
1227 * @param string $moduleName Name of module to check.
1230 public static function apacheModulePresent( $moduleName ) {
1231 if ( function_exists( 'apache_get_modules' ) && in_array( $moduleName, apache_get_modules() ) ) {
1234 // try it the hard way
1236 phpinfo( INFO_MODULES
);
1237 $info = ob_get_clean();
1239 return strpos( $info, $moduleName ) !== false;
1243 * ParserOptions are constructed before we determined the language, so fix it
1245 * @param Language $lang
1247 public function setParserLanguage( $lang ) {
1248 $this->parserOptions
->setTargetLanguage( $lang );
1249 $this->parserOptions
->setUserLang( $lang );
1253 * Overridden by WebInstaller to provide lastPage parameters.
1254 * @param string $page
1257 protected function getDocUrl( $page ) {
1258 return "{$_SERVER['PHP_SELF']}?page=" . urlencode( $page );
1262 * Find extensions or skins in a subdirectory of $IP.
1263 * Returns an array containing the value for 'Name' for each found extension.
1265 * @param string $directory Directory to search in, relative to $IP, must be either "extensions"
1267 * @return array [ $extName => [ 'screenshots' => [ '...' ] ]
1269 public function findExtensions( $directory = 'extensions' ) {
1270 switch ( $directory ) {
1272 return $this->findExtensionsByType( 'extension', 'extensions' );
1274 return $this->findExtensionsByType( 'skin', 'skins' );
1276 throw new InvalidArgumentException( "Invalid extension type" );
1281 * Find extensions or skins, and return an array containing the value for 'Name' for each found
1284 * @param string $type Either "extension" or "skin"
1285 * @param string $directory Directory to search in, relative to $IP
1286 * @return array [ $extName => [ 'screenshots' => [ '...' ] ]
1288 protected function findExtensionsByType( $type = 'extension', $directory = 'extensions' ) {
1289 if ( $this->getVar( 'IP' ) === null ) {
1293 $extDir = $this->getVar( 'IP' ) . '/' . $directory;
1294 if ( !is_readable( $extDir ) ||
!is_dir( $extDir ) ) {
1298 $dh = opendir( $extDir );
1300 while ( ( $file = readdir( $dh ) ) !== false ) {
1301 if ( !is_dir( "$extDir/$file" ) ) {
1304 $status = $this->getExtensionInfo( $type, $directory, $file );
1305 if ( $status->isOK() ) {
1306 $exts[$file] = $status->value
;
1310 uksort( $exts, 'strnatcasecmp' );
1316 * @param string $type Either "extension" or "skin"
1317 * @param string $parentRelPath The parent directory relative to $IP
1318 * @param string $name The extension or skin name
1319 * @return Status An object containing an error list. If there were no errors, an associative
1320 * array of information about the extension can be found in $status->value.
1322 protected function getExtensionInfo( $type, $parentRelPath, $name ) {
1323 if ( $this->getVar( 'IP' ) === null ) {
1324 throw new Exception( 'Cannot find extensions since the IP variable is not yet set' );
1326 if ( $type !== 'extension' && $type !== 'skin' ) {
1327 throw new InvalidArgumentException( "Invalid extension type" );
1329 $absDir = $this->getVar( 'IP' ) . "/$parentRelPath/$name";
1330 $relDir = "../$parentRelPath/$name";
1331 if ( !is_dir( $absDir ) ) {
1332 return Status
::newFatal( 'config-extension-not-found', $name );
1334 $jsonFile = $type . '.json';
1335 $fullJsonFile = "$absDir/$jsonFile";
1336 $isJson = file_exists( $fullJsonFile );
1339 // Only fallback to PHP file if JSON doesn't exist
1340 $fullPhpFile = "$absDir/$name.php";
1341 $isPhp = file_exists( $fullPhpFile );
1343 if ( !$isJson && !$isPhp ) {
1344 return Status
::newFatal( 'config-extension-not-found', $name );
1347 // Extension exists. Now see if there are screenshots
1349 if ( is_dir( "$absDir/screenshots" ) ) {
1350 $paths = glob( "$absDir/screenshots/*.png" );
1351 foreach ( $paths as $path ) {
1352 $info['screenshots'][] = str_replace( $absDir, $relDir, $path );
1357 $jsonStatus = $this->readExtension( $fullJsonFile );
1358 if ( !$jsonStatus->isOK() ) {
1361 $info +
= $jsonStatus->value
;
1364 return Status
::newGood( $info );
1368 * @param string $fullJsonFile
1369 * @param array $extDeps
1370 * @param array $skinDeps
1372 * @return Status On success, an array of extension information is in $status->value. On
1373 * failure, the Status object will have an error list.
1375 private function readExtension( $fullJsonFile, $extDeps = [], $skinDeps = [] ) {
1380 $extDir = $this->getVar( 'IP' ) . '/extensions';
1381 foreach ( $extDeps as $dep ) {
1382 $fname = "$extDir/$dep/extension.json";
1383 if ( !file_exists( $fname ) ) {
1384 return Status
::newFatal( 'config-extension-not-found', $dep );
1390 $skinDir = $this->getVar( 'IP' ) . '/skins';
1391 foreach ( $skinDeps as $dep ) {
1392 $fname = "$skinDir/$dep/skin.json";
1393 if ( !file_exists( $fname ) ) {
1394 return Status
::newFatal( 'config-extension-not-found', $dep );
1399 $registry = new ExtensionRegistry();
1401 $info = $registry->readFromQueue( $load );
1402 } catch ( ExtensionDependencyError
$e ) {
1403 if ( $e->incompatibleCore ||
$e->incompatibleSkins
1404 ||
$e->incompatibleExtensions
1406 // If something is incompatible with a dependency, we have no real
1407 // option besides skipping it
1408 return Status
::newFatal( 'config-extension-dependency',
1409 basename( dirname( $fullJsonFile ) ), $e->getMessage() );
1410 } elseif ( $e->missingExtensions ||
$e->missingSkins
) {
1411 // There's an extension missing in the dependency tree,
1412 // so add those to the dependency list and try again
1413 return $this->readExtension(
1415 array_merge( $extDeps, $e->missingExtensions
),
1416 array_merge( $skinDeps, $e->missingSkins
)
1419 // Some other kind of dependency error?
1420 return Status
::newFatal( 'config-extension-dependency',
1421 basename( dirname( $fullJsonFile ) ), $e->getMessage() );
1424 // The order of credits will be the order of $load,
1425 // so the first extension is the one we want to load,
1426 // everything else is a dependency
1428 foreach ( $info['credits'] as $name => $credit ) {
1431 // Extension we want to load
1434 $type = basename( $credit['path'] ) === 'skin.json' ?
'skins' : 'extensions';
1435 $ret['requires'][$type][] = $credit['name'];
1437 $credits = array_values( $info['credits'] )[0];
1438 if ( isset( $credits['url'] ) ) {
1439 $ret['url'] = $credits['url'];
1441 $ret['type'] = $credits['type'];
1443 return Status
::newGood( $ret );
1447 * Returns a default value to be used for $wgDefaultSkin: normally the one set in DefaultSettings,
1448 * but will fall back to another if the default skin is missing and some other one is present
1451 * @param string[] $skinNames Names of installed skins.
1454 public function getDefaultSkin( array $skinNames ) {
1455 $defaultSkin = $GLOBALS['wgDefaultSkin'];
1456 if ( !$skinNames ||
in_array( $defaultSkin, $skinNames ) ) {
1457 return $defaultSkin;
1459 return $skinNames[0];
1464 * Installs the auto-detected extensions.
1466 * @suppress SecurityCheck-OTHER It thinks $exts/$IP is user controlled but they are not.
1469 protected function includeExtensions() {
1471 $exts = $this->getVar( '_Extensions' );
1472 $IP = $this->getVar( 'IP' );
1474 // Marker for DatabaseUpdater::loadExtensions so we don't
1475 // double load extensions
1476 define( 'MW_EXTENSIONS_LOADED', true );
1479 * We need to include DefaultSettings before including extensions to avoid
1480 * warnings about unset variables. However, the only thing we really
1481 * want here is $wgHooks['LoadExtensionSchemaUpdates']. This won't work
1482 * if the extension has hidden hook registration in $wgExtensionFunctions,
1483 * but we're not opening that can of worms
1484 * @see https://phabricator.wikimedia.org/T28857
1486 global $wgAutoloadClasses;
1487 $wgAutoloadClasses = [];
1490 require "$IP/includes/DefaultSettings.php";
1492 foreach ( $exts as $e ) {
1493 if ( file_exists( "$IP/extensions/$e/extension.json" ) ) {
1494 $queue["$IP/extensions/$e/extension.json"] = 1;
1496 require_once "$IP/extensions/$e/$e.php";
1500 $registry = new ExtensionRegistry();
1501 $data = $registry->readFromQueue( $queue );
1502 $wgAutoloadClasses +
= $data['autoload'];
1504 // @phan-suppress-next-line PhanUndeclaredVariable $wgHooks is set by DefaultSettings
1505 $hooksWeWant = $wgHooks['LoadExtensionSchemaUpdates'] ??
[];
1507 if ( isset( $data['globals']['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
1508 $hooksWeWant = array_merge_recursive(
1510 $data['globals']['wgHooks']['LoadExtensionSchemaUpdates']
1513 // Unset everyone else's hooks. Lord knows what someone might be doing
1514 // in ParserFirstCallInit (see T29171)
1515 $GLOBALS['wgHooks'] = [ 'LoadExtensionSchemaUpdates' => $hooksWeWant ];
1517 return Status
::newGood();
1521 * Get an array of install steps. Should always be in the format of
1523 * 'name' => 'someuniquename',
1524 * 'callback' => [ $obj, 'method' ],
1526 * There must be a config-install-$name message defined per step, which will
1527 * be shown on install.
1529 * @param DatabaseInstaller $installer DatabaseInstaller so we can make callbacks
1532 protected function getInstallSteps( DatabaseInstaller
$installer ) {
1533 $coreInstallSteps = [
1534 [ 'name' => 'database', 'callback' => [ $installer, 'setupDatabase' ] ],
1535 [ 'name' => 'tables', 'callback' => [ $installer, 'createTables' ] ],
1536 [ 'name' => 'interwiki', 'callback' => [ $installer, 'populateInterwikiTable' ] ],
1537 [ 'name' => 'stats', 'callback' => [ $this, 'populateSiteStats' ] ],
1538 [ 'name' => 'keys', 'callback' => [ $this, 'generateKeys' ] ],
1539 [ 'name' => 'updates', 'callback' => [ $installer, 'insertUpdateKeys' ] ],
1540 [ 'name' => 'sysop', 'callback' => [ $this, 'createSysop' ] ],
1541 [ 'name' => 'mainpage', 'callback' => [ $this, 'createMainpage' ] ],
1544 // Build the array of install steps starting from the core install list,
1545 // then adding any callbacks that wanted to attach after a given step
1546 foreach ( $coreInstallSteps as $step ) {
1547 $this->installSteps
[] = $step;
1548 if ( isset( $this->extraInstallSteps
[$step['name']] ) ) {
1549 $this->installSteps
= array_merge(
1550 $this->installSteps
,
1551 $this->extraInstallSteps
[$step['name']]
1556 // Prepend any steps that want to be at the beginning
1557 if ( isset( $this->extraInstallSteps
['BEGINNING'] ) ) {
1558 $this->installSteps
= array_merge(
1559 $this->extraInstallSteps
['BEGINNING'],
1564 // Extensions should always go first, chance to tie into hooks and such
1565 if ( count( $this->getVar( '_Extensions' ) ) ) {
1566 array_unshift( $this->installSteps
,
1567 [ 'name' => 'extensions', 'callback' => [ $this, 'includeExtensions' ] ]
1569 $this->installSteps
[] = [
1570 'name' => 'extension-tables',
1571 'callback' => [ $installer, 'createExtensionTables' ]
1575 return $this->installSteps
;
1579 * Actually perform the installation.
1581 * @param callable $startCB A callback array for the beginning of each step
1582 * @param callable $endCB A callback array for the end of each step
1584 * @return array Array of Status objects
1586 public function performInstallation( $startCB, $endCB ) {
1587 $installResults = [];
1588 $installer = $this->getDBInstaller();
1589 $installer->preInstall();
1590 $steps = $this->getInstallSteps( $installer );
1591 foreach ( $steps as $stepObj ) {
1592 $name = $stepObj['name'];
1593 call_user_func_array( $startCB, [ $name ] );
1595 // Perform the callback step
1596 $status = call_user_func( $stepObj['callback'], $installer );
1598 // Output and save the results
1599 call_user_func( $endCB, $name, $status );
1600 $installResults[$name] = $status;
1602 // If we've hit some sort of fatal, we need to bail.
1603 // Callback already had a chance to do output above.
1604 if ( !$status->isOk() ) {
1608 if ( $status->isOk() ) {
1610 'config-install-success',
1611 $this->getVar( 'wgServer' ),
1612 $this->getVar( 'wgScriptPath' )
1614 $this->setVar( '_InstallDone', true );
1617 return $installResults;
1621 * Generate $wgSecretKey. Will warn if we had to use an insecure random source.
1625 public function generateKeys() {
1626 $keys = [ 'wgSecretKey' => 64 ];
1627 if ( strval( $this->getVar( 'wgUpgradeKey' ) ) === '' ) {
1628 $keys['wgUpgradeKey'] = 16;
1631 return $this->doGenerateKeys( $keys );
1635 * Generate a secret value for variables using a secure generator.
1637 * @param array $keys
1640 protected function doGenerateKeys( $keys ) {
1641 $status = Status
::newGood();
1643 foreach ( $keys as $name => $length ) {
1644 $secretKey = MWCryptRand
::generateHex( $length );
1645 $this->setVar( $name, $secretKey );
1652 * Create the first user account, grant it sysop, bureaucrat and interface-admin rights
1656 protected function createSysop() {
1657 $name = $this->getVar( '_AdminName' );
1658 $user = User
::newFromName( $name );
1661 // We should've validated this earlier anyway!
1662 return Status
::newFatal( 'config-admin-error-user', $name );
1665 if ( $user->idForName() == 0 ) {
1666 $user->addToDatabase();
1669 $user->setPassword( $this->getVar( '_AdminPassword' ) );
1670 } catch ( PasswordError
$pwe ) {
1671 return Status
::newFatal( 'config-admin-error-password', $name, $pwe->getMessage() );
1674 $user->addGroup( 'sysop' );
1675 $user->addGroup( 'bureaucrat' );
1676 $user->addGroup( 'interface-admin' );
1677 if ( $this->getVar( '_AdminEmail' ) ) {
1678 $user->setEmail( $this->getVar( '_AdminEmail' ) );
1680 $user->saveSettings();
1682 // Update user count
1683 $ssUpdate = SiteStatsUpdate
::factory( [ 'users' => 1 ] );
1684 $ssUpdate->doUpdate();
1686 $status = Status
::newGood();
1688 if ( $this->getVar( '_Subscribe' ) && $this->getVar( '_AdminEmail' ) ) {
1689 $this->subscribeToMediaWikiAnnounce( $status );
1698 private function subscribeToMediaWikiAnnounce( Status
$s ) {
1700 'email' => $this->getVar( '_AdminEmail' ),
1705 // Mailman doesn't support as many languages as we do, so check to make
1706 // sure their selected language is available
1707 $myLang = $this->getVar( '_UserLang' );
1708 if ( in_array( $myLang, $this->mediaWikiAnnounceLanguages
) ) {
1709 $myLang = $myLang == 'pt-br' ?
'pt_BR' : $myLang; // rewrite to Mailman's pt_BR
1710 $params['language'] = $myLang;
1713 if ( MWHttpRequest
::canMakeRequests() ) {
1714 $res = MWHttpRequest
::factory( $this->mediaWikiAnnounceUrl
,
1715 [ 'method' => 'POST', 'postData' => $params ], __METHOD__
)->execute();
1716 if ( !$res->isOK() ) {
1717 $s->warning( 'config-install-subscribe-fail', $res->getMessage() );
1720 $s->warning( 'config-install-subscribe-notpossible' );
1725 * Insert Main Page with default content.
1727 * @param DatabaseInstaller $installer
1730 protected function createMainpage( DatabaseInstaller
$installer ) {
1731 $status = Status
::newGood();
1732 $title = Title
::newMainPage();
1733 if ( $title->exists() ) {
1734 $status->warning( 'config-install-mainpage-exists' );
1738 $page = WikiPage
::factory( $title );
1739 $content = new WikitextContent(
1740 wfMessage( 'mainpagetext' )->inContentLanguage()->text() . "\n\n" .
1741 wfMessage( 'mainpagedocfooter' )->inContentLanguage()->text()
1744 $status = $page->doEditContent( $content,
1748 User
::newFromName( 'MediaWiki default' )
1750 } catch ( Exception
$e ) {
1751 // using raw, because $wgShowExceptionDetails can not be set yet
1752 $status->fatal( 'config-install-mainpage-failed', $e->getMessage() );
1759 * Override the necessary bits of the config to run an installation.
1761 public static function overrideConfig() {
1762 // Use PHP's built-in session handling, since MediaWiki's
1763 // SessionHandler can't work before we have an object cache set up.
1764 define( 'MW_NO_SESSION_HANDLER', 1 );
1766 // Don't access the database
1767 $GLOBALS['wgUseDatabaseMessages'] = false;
1768 // Don't cache langconv tables
1769 $GLOBALS['wgLanguageConverterCacheType'] = CACHE_NONE
;
1771 $GLOBALS['wgShowExceptionDetails'] = true;
1772 $GLOBALS['wgShowHostnames'] = true;
1773 // Don't break forms
1774 $GLOBALS['wgExternalLinkTarget'] = '_blank';
1776 // Allow multiple ob_flush() calls
1777 $GLOBALS['wgDisableOutputCompression'] = true;
1779 // Use a sensible cookie prefix (not my_wiki)
1780 $GLOBALS['wgCookiePrefix'] = 'mw_installer';
1782 // Some of the environment checks make shell requests, remove limits
1783 $GLOBALS['wgMaxShellMemory'] = 0;
1785 // Override the default CookieSessionProvider with a dummy
1786 // implementation that won't stomp on PHP's cookies.
1787 $GLOBALS['wgSessionProviders'] = [
1789 'class' => InstallerSessionProvider
::class,
1796 // Don't try to use any object cache for SessionManager either.
1797 $GLOBALS['wgSessionCacheType'] = CACHE_NONE
;
1801 * Add an installation step following the given step.
1803 * @param callable $callback A valid installation callback array, in this form:
1804 * [ 'name' => 'some-unique-name', 'callback' => [ $obj, 'function' ] ];
1805 * @param string $findStep The step to find. Omit to put the step at the beginning
1807 public function addInstallStep( $callback, $findStep = 'BEGINNING' ) {
1808 $this->extraInstallSteps
[$findStep][] = $callback;
1812 * Disable the time limit for execution.
1813 * Some long-running pages (Install, Upgrade) will want to do this
1815 protected function disableTimeLimit() {
1816 Wikimedia\
suppressWarnings();
1817 set_time_limit( 0 );
1818 Wikimedia\restoreWarnings
();